package admin

import (
	"archive/zip"
	"fmt"
	"io"
	"os"
	"path"
	"regexp"
	"strconv"
	"strings"
	"tcsc/controllers/mobile"
	"tcsc/models"
	"tcsc/sword"
	"time"

	_ "image/gif"
	_ "image/jpeg"
	_ "image/png"

	"github.com/360EntSecGroup-Skylar/excelize"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type Product struct {
	BaseController
}

func (c *Product) Get() {
	column1 := models.Query(`select id,name,pid,level from mt_column where type='p' and status=1 and pid=0`)
	c.Data["column1"] = column1
	//beego.Debug(column1)
	column2 := models.Query(`select id,name from mt_column where type='p' and status=1 and pid=` + column1[0]["id"].(string))
	c.Data["column2"] = column2
	c.Data["column3"] = models.Query(`select id,name from mt_column where type='p' and status=1 and pid=` + column2[0]["id"].(string))
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	pstyle := c.GetString("pstyle")
	c.Data["pstyle"] = pstyle
	var w []string
	id := c.GetString("id")
	c.Data["id"] = id
	w = append(w, `a.status=1`)
	if c.Gid != "0" {
		w = append(w, `a.gid=`+c.Gid)
	} else {
		if id != "" {
			w = append(w, `a.gid=`+id)
		} else {
			w = append(w, `(a.gid=0 or d.style=0)`)
		}
	}
	var urlc = "/admin/shop/product?"
	censoring := c.GetString("censoring")
	recommend := c.GetString("recommend")
	is_show := c.GetString("is_show")
	c.Data["censoring"] = censoring
	c.Data["recommend"] = recommend
	c.Data["is_show"] = is_show
	if censoring != "" {
		urlc += "censoring=" + censoring + "&"
		w = append(w, `a.censoring=`+censoring)
	}
	if recommend != "" {
		urlc += "recommend=" + recommend + "&"
		w = append(w, `a.recommend=`+recommend)
	}
	if is_show != "" {
		urlc += "is_show=" + is_show + "&"
		w = append(w, `a.is_show=`+is_show)
	}
	bid := c.GetString("bid")
	if bid != "" {
		w = append(w, `a.bid=`+bid)
	}
	search := c.GetString("search")
	c.Data["search"] = search
	cid := c.GetString("cid")
	c.Data["cid"] = cid
	if search != "" {
		// urlc += "search=" + search + "&"
		w = append(w, `(a.title like '%`+search+`%' or a.model like '%`+search+`%' or a.keywords like '%`+search+`%')`)
	} else {
		if cid != "" {
			var cids []string
			if c.Gid == "0" {
				column := models.Query(`select id from mt_column where pid=` + cid + ` and status=1 and gid=` + c.Gid)
				for _, v := range column {
					id := v["id"].(string)
					cids = append(cids, id)
					columnson := models.Query(`select id from mt_column where pid=` + id + ` and status=1 and gid=` + c.Gid)
					for _, s := range columnson {
						cids = append(cids, s["id"].(string))
					}
				}
				cidss := strings.Join(cids, ",")
				if cidss != "" {
					w = append(w, `a.cid in (`+cidss+`)`)
				}
			} else {
				w = append(w, `a.cid = `+cid)
			}
		}
	}
	// w = append(w, `a.gid=`+c.Gid)
	ws := strings.Join(w, ` and `)
	lt := ` limit ` + page + `,` + num
	sql := `select a.*,b.name as cname,c.pathname,d.name as gname from mt_product a left join mt_column b on a.cid=b.id left join mt_resources c 
	on a.img=c.id left join mt_shop d on d.id=a.gid where ` + ws + ` order by a.censoring desc,a.recommend desc` + lt
	//beego.Debug(sql)
	sql2 := `select count(a.id) as totals from mt_product a left join mt_shop d on a.gid=d.id where ` + ws
	info := models.Query(sql)
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	if id != "" {
		c.Data["url"] = urlc + "bid=" + bid + "&id=" + id + "&search=" + search + "&"
		c.Data["urlc"] = "/admin/shop/product?bid=" + bid + "&id=" + id + "&"
	} else {
		c.Data["url"] = urlc + "bid=" + bid + "&search=" + search + "&"
		c.Data["urlc"] = "/admin/shop/product?bid=" + bid + "&"
	}
	c.TplName = "admin/product/index.html"
}

func (c *Product) Post() {
	defer c.ServeJSON()
	json := make(map[string]interface{})
	c.Data["json"] = &json
	_type := c.GetString("type")
	if _type == "1" {
		if c.GetSession("mergeSuccess") == "1" {
			json["status"] = "1"
		} else if c.GetSession("mergeSuccess") == "0" {
			json["status"] = "0"
		}
		c.DelSession("mergeSuccess")
		return
	}
	freight := models.Query(`select freight from mt_shop where id=?`, c.Gid)[0]["freight"].(string)
	if shop := models.Query(`select id from mt_shop where status=1 and censoring=1 and style=0`); shop != nil {
		var gid []string
		gid = append(gid, "0")
		for _, v := range shop {
			gid = append(gid, v["id"].(string))
		}
		gids := strings.Join(gid, ",")

		if products := models.Query(`select * from mt_product where status=1 and censoring=1 and gid in (` + gids + `)`); products != nil {
			for _, v := range products {
				if v["barcode"] != nil {
					length := v["length"].(string)
					width := v["width"].(string)
					height := v["height"].(string)
					number := v["number"].(string)
					volume := sword.Divi(sword.Mult(length, sword.Mult(width, height)), "1000000")
					cellFreight := sword.Divi(sword.Mult(freight, volume), number)
					price := v["price"].(string)
					if v["isvip"].(string) == "1" {
						fold := models.Query(`select fold from mt_member_vip where status=1 and name='金钻会员'`)[0]["fold"].(string)
						price = sword.Divi(sword.Mult(price, fold), "100")
					}
					endPrice := sword.Mult(sword.Sum(price, cellFreight), "3")
					if product := models.Query(`select id from mt_product where status=1 and censoring=1 and gid=? and barcode=?`, c.Gid, v["barcode"]); product != nil {
						if err := models.Exec(`update mt_product set price=?,mprice=? where id=?`, endPrice, v["mprice"], product[0]["id"]); err != nil {
							beego.Debug(err)
							json["status"] = "0"
							c.SetSession("mergeSuccess", "0")
							return
						}
					} else {
						nowtime := time.Now().Local().Format("2006-01-02 15:04:05")
						v["price"] = endPrice
						v["gid"] = c.Gid
						v["addtime"] = nowtime
						if fmt.Sprint(v["issellnum"]) == "1" {
							sellnum := models.Query(`select sum(a.num) as num from mt_order_car a where a.status>1 and a.pid=` + v["id"].(string))[0]["num"]
							if sellnums, ok := sellnum.(string); ok {
								v["sellnum"] = sellnums
							} else {
								v["sellnum"] = "0"
							}
						}
						sql, params := makesql(v, "mt_product")
						err := models.Exec(sql, params...)

						// err := models.Exec(`insert into mt_product
						// 	select 0,?,cid,gcid,bid,title,keywords,description,img,image,video,content,model,'0',sort,ispromote,
						// 	click,wholesale,isintegral,censoring,recommend,status,?,null,lang,attr,length,width,height,weight,number,
						// 	?,mprice,spec,isvip,inventory,sellnum,issellnum,good,recom,mbuy,grecommend,gsort,isw,barcode,size
						// 	from mt_product where id=?`,c.Gid , nowtime, endPrice, v["id"])
						if err != nil {
							beego.Debug(err)
							json["status"] = "0"
							c.SetSession("mergeSuccess", "0")
							return
						}
					}
				}
			}
			c.SetSession("mergeSuccess", "1")
			json["status"] = "1"
		}
	}
}

func makesql(res orm.Params, table string) (sql string, params []interface{}) {
	var field []string
	var value []string
	for k, v := range res {
		if v != "" && v != nil && k != "id" {
			field = append(field, "`"+k+"`")
			value = append(value, "?")
			params = append(params, v)
		}
	}
	field_str := strings.Join(field, ",")
	value_str := strings.Join(value, ",")
	sql = "insert into " + table + "(" + field_str + ") values(" + value_str + ")"
	return
}

type ProductNew struct {
	BaseController
}

func (c *ProductNew) Get() {
	gid := c.Gid
	if gid == "0" {
		c.Ctx.Redirect(302, "/admin/product/index")
		return
	}
	var t string
	time1 := "2019-02-23 00:00:00"
	time2 := models.Query(`select addtime from mt_shop where id=?`, gid)[0]["addtime"].(string)
	t1, _ := time.Parse("2006-01-02 15:04:05", time1)
	t2, _ := time.Parse("2006-01-02 15:04:05", time2)
	if t1.Before(t2) {
		t = time2
	} else {
		t = time1
	}
	search := c.GetString("search")
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	lt := ` limit ` + page + `,` + num
	var w []string
	w = append(w, `a.gid=`+gid)
	w = append(w, `a.status=1`)
	// w = append(w, `a.censoring=1`)
	w = append(w, `a.addtime>'`+t+`'`)
	if search != "" {
		w = append(w, `(a.title like '%`+search+`%' or a.model like '%`+search+`%' or a.keywords like '%`+search+`%')`)
	}
	ws := strings.Join(w, ` and `)
	info := models.Query(`select a.*,b.name as cname,c.pathname from mt_product a left join mt_column b on a.cid=b.id left join mt_resources c 
	on a.img=c.id where ` + ws + ` order by a.censoring,addtime desc  ` + lt)
	pageSql := `select count(a.id) as totals from mt_product a where ` + ws
	c.Data["paginator"] = models.Page(pageSql, page2, num)
	c.Data["url"] = `/admin/product/new?search=` + search + `&`
	c.Data["info"] = info
	c.TplName = "admin/product/new.html"
}

type ProductAE struct {
	BaseController
}

func (c *ProductAE) Get() {
	column1 := models.Query(`select id,name from mt_column where type='p' and status=1 and pid=0 and gid=0`)
	c.Data["adminC"] = models.Query(`select permission,gid from mt_systems_admin where status=1 and censoring=1 and id=` + c.Qid)[0]
	c.Data["column1"] = column1
	id := c.GetString("id")
	if len(column1) > 0 && id == "" {
		column2 := models.Query(`select id,name from mt_column where type='p' and status=1 and gid=0 and pid=` + column1[0]["id"].(string))
		for _, v := range column2 {
			attribute := models.Query(`select id,name from mt_product_attribute_column where cid=` + v["id"].(string) + ` order by sort desc`)
			for _, a := range attribute {
				a["attribute"] = models.Query(`select id,name from mt_product_attribute where cid=` + a["id"].(string) + ` order by sort desc`)
			}
			v["acolumn"] = attribute
		}
		c.Data["column2"] = column2
		if len(column2) > 0 {
			c.Data["column3"] = models.Query(`select id,name from mt_column where type='p' and status=1 and gid=0 and pid=` + column2[0]["id"].(string))
		}
	}
	gcolumn := models.Query(`select id,name from mt_column where type='p' and status=1 and pid=0 and gid=` + c.Gid)
	c.Data["gcolumn"] = gcolumn

	/*	if c.Gid != "0" {
			c.Data["brand"] = models.Query(`select id,name from mt_brand where status=1 and gid=` + c.Gid)
		} else {
		}*/ // (select * from mt_shop where style=0)
	c.Data["brand"] = models.Query(`select a.id,a.name,b.id as gid from mt_brand a left join mt_shop b on a.id=b.bid where a.status=1`)
	imgs := make(map[int]string)
	picnum := make(map[int]string)
	for i := 0; i < 4; i++ {
		imgs[i] = "/static/img/admin/uppic.png"
		picnum[i] = ""
	}
	if id != "" {
		info := models.Query(`select a.*,b.pathname from mt_product a left join mt_resources b on a.img=b.id where a.id=` + id)[0]
		picture := fmt.Sprint(info["image"])
		if picture != "" && picture != "<nil>" {
			if imgss := models.Query(fmt.Sprintf(`select id,pathname from mt_resources where id in(%v)`, picture)); imgss != nil {
				for k, v := range imgss {
					imgs[k] = fmt.Sprint(v["pathname"])
					picnum[k] = fmt.Sprint(v["id"])
				}
			}
		}
		cid := fmt.Sprint(info["cid"])
		if cid != "" && cid != "<nil>" {
			cids := models.Query(`select level,pid from mt_column where id=` + cid)[0]
			level := cids["level"]
			if fmt.Sprint(level) == "2" {
				column2 := models.Query(`select id,name from mt_column where type='p' and status=1 and gid=0 and pid=` + cids["pid"].(string))
				for _, v := range column2 {
					attribute := models.Query(`select id,name from mt_product_attribute_column where cid=` + v["id"].(string) + ` order by sort desc`)
					for _, a := range attribute {
						a["attribute"] = models.Query(`select id,name from mt_product_attribute where cid=` + a["id"].(string) + ` order by sort desc`)
					}
					v["acolumn"] = attribute
				}
				c.Data["column2"] = column2
				info["cid1"] = cids["pid"]
				info["cid2"] = cid
				c.Data["column3"] = nil
			} else if fmt.Sprint(level) == "3" {
				c.Data["column3"] = models.Query(`select id,name from mt_column where type='p' and status=1 and gid=0 and pid=` + cids["pid"].(string))
				info["cid3"] = cid
				info["cid2"] = cids["pid"]
				cids2 := models.Query(`select pid from mt_column where id=` + cids["pid"].(string))[0]
				info["cid1"] = cids2["pid"]
				column2 := models.Query(`select id,name from mt_column where type='p' and status=1 and gid=0 and pid=` + cids2["pid"].(string))
				for _, v := range column2 {
					attribute := models.Query(`select id,name from mt_product_attribute_column where status=1 and cid=` + v["id"].(string) + ` order by sort desc`)
					for _, a := range attribute {
						a["attribute"] = models.Query(`select id,name from mt_product_attribute where status=1 and cid=` + a["id"].(string) + ` order by sort desc`)
					}
					v["acolumn"] = attribute
				}
				c.Data["column2"] = column2
			} else {
				info["cid1"] = cid
			}
		}
		c.Data["info"] = info
	}

	proStruct := models.Query(`select id,name,pid from mt_goods_struct where status=1 and gid=?`, c.Gid)
	c.Data["proStruct"] = proStruct
	c.Data["imgs"] = imgs
	c.Data["picnum"] = picnum
	c.TplName = "admin/product/ae.html"
}
func (c *ProductAE) Post() {
	defer c.ServeJSON()
	gid := c.Gid
	input := c.Input()
	synchronize := input["synchronize"][0]
	delete(input, "synchronize")
	productStruct := strings.Replace(strings.Trim(strings.Join(c.GetStrings("productstruct"), ","), ","), ",,", ",", -1)
	input.Set("productstruct", productStruct)
	input.Set("content", sword.CkeditorChange(c.GetString("content")))
	input.Set("image", strings.Replace(strings.Trim(strings.Join(c.GetStrings("image"), ","), ","), ",,", ",", -1))
	if c.GetString("attr") != "" {
		input.Set("attr", strings.Replace(strings.Trim(strings.Join(c.GetStrings("attr"), ","), ","), ",,", ",", -1)+",")
	}
	// if gid == "0" {
	if input.Get("cid3") != "" {
		input.Set("cid", input.Get("cid3"))
	} else {
		if input.Get("cid2") != "" {
			input.Set("cid", input.Get("cid2"))
		} else {
			input.Set("cid", input.Get("cid1"))
		}
	}
	// } else {
	// 	input.Set("cid", input.Get("gcid"))
	// }
	input.Set("modifytime", time.Now().Format("2006-01-02 15:04:05"))
	input.Del("cid1")
	input.Del("cid2")
	input.Del("cid3")
	if input.Get("id") == "" {
		input.Set("addtime", sword.Gettimes("2006-01-02 15:04:05"))
		// 判断条码是否重复
		barcode := input.Get("barcode")
		record := models.Query("select a.* from mt_product a left join mt_column b on a.cid=b.id left join mt_resources c  on a.img=c.id left join mt_shop d on d.id=a.gid where a.status=1 AND ( a.gid = 0 OR d.style = 0 )  and a.barcode = ?", barcode)
		if record != nil {
			c.Data["json"] = map[string]interface{}{
				"status": -1,
				"msg":    fmt.Sprintf("条形码和  %v 重复", record[0]["title"]),
			}
			return
		}

	} else {
		input.Set("modifytime", sword.Gettimes("2006-01-02 15:04:05"))
		// 判断条码是否重复
		barcode := input.Get("barcode")
		id := input.Get("id")
		record := models.Query("select a.* from mt_product a left join mt_column b on a.cid=b.id left join mt_resources c  on a.img=c.id left join mt_shop d on d.id=a.gid where a.status=1 AND ( a.gid = 0 OR d.style = 0 )  and a.barcode = ? and a.id != ?", barcode, id)
		if record != nil {
			c.Data["json"] = map[string]interface{}{
				"status": -1,
				"msg":    fmt.Sprintf("条形码和  %v 重复", record[0]["title"]),
			}
			return
		}
	}
	id := input.Get("id")
	if gid != "0" {
		input.Set("gid", gid)
	}
	if input.Get("issellnum") == "1" {
		sellnum := models.Query(`select * from mt_order_car where status>1 and pid=? and gid=?`, input.Get("id"), gid)
		if sellnum == nil {
			input.Set("sellnum", "0")
		} else {
			input.Set("sellnum", sellnum[0]["num"].(string))
		}
	}
	var oldp orm.Params
	if id != "" {
		oldp = models.Query(`select price from mt_product where id=?`, id)[0]
	}
	if gid == "0" {
		price := sword.Mult(input.Get("price"), fmt.Sprint(models.Systems()["mult"]))
		input.Set("mprice", input.Get("price"))
		input.Set("price", price)
		input.Set("platform", "0")
	} else {
		if shop := models.Query(`select style from mt_shop where id=` + gid); shop != nil {
			if fmt.Sprint(shop[0]["style"]) == "0" {
				input.Del("mprice")
				input.Set("price", input.Get("price"))
				input.Set("platform", "0")
			}
		}
		input.Set("platform", "1")
	}
	res, err := models.Save("mt_product", input)
	if synchronize == "2" {
		ids := models.Query(`select id,gid from mt_product where status=1 and censoring=1 and barcode=` + input.Get("barcode"))
		comInput := input
		for _, v := range ids {
			if v["gid"].(string) != "0" {
				shop := models.Query(`select a.id,a.freight,a.freight,a.name,a.uid,b.wx_openid_gzh as openid from mt_shop a left join mt_member b on a.uid=b.id where a.status=1 and a.censoring=1 and a.style=1 and a.id=` + v["gid"].(string))
				volume := sword.Divi(sword.Mult(input.Get("length"), sword.Mult(input.Get("width"), input.Get("height"))), "1000000")
				var cellFreight string
				if shop != nil {
					for _, v := range shop {
						if v["freight"].(string) == "0" {
							cellFreight = "0"
						} else {
							cellFreight = sword.Divi(sword.Mult(v["freight"].(string), volume), input.Get("number"))
						}
					}
				}
				endPrice := sword.Mult(sword.Sum(comInput.Get("mprice"), cellFreight), "3")
				comInput.Del("gid")
				comInput.Del("gsort")
				comInput.Del("sellnum")
				comInput.Del("sellnum")
				comInput.Del("isvip")
				comInput.Del("ispromote")
				comInput.Del("platform")
				comInput.Del("click")
				comInput.Del("recommend")
				comInput.Del("mbuy")
				comInput.Del("grecommend")
				comInput.Del("good")
				comInput.Del("issellnum")
				comInput.Del("sort")
				comInput.Del("minbuy")
				comInput.Del("recom")
				comInput.Del("inventory")
				comInput.Del("censoring")
				comInput.Set("id", v["id"].(string))
				comInput.Set("price", endPrice)
				res, err = models.Save("mt_product", comInput)
				if shop != nil {
					for _, v := range shop {
						data4 := map[string]map[string]interface{}{
							"first":    {"value": `总部产品信息调整`},
							"keyword1": {"value": fmt.Sprint(v["name"]), "color": `#36353A`},
							"keyword2": {"value": comInput.Get("title"), "color": `#e31939`},
							"keyword3": {"value": comInput.Get("price"), "color": "#36353A"},
							"remark":   {"value": `您可以在后台重新调整自己的产品`},
						}
						models.Push(v["openid"].(string), `JghVEqYW2gpPyGpdqEvhERS1AQUxTtsAwEQqjr8BOJI`, data4, models.Urlc+"/mobile/column/product_content?id="+strconv.FormatInt(res, 10), "")
					}
				}
			}
		}
	}
	if err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		proId := strconv.FormatInt(res, 10)
		SetProImgWatermark(proId)
		if id != "" {
			beego.Debug(oldp["price"], input.Get("price"))
			if fmt.Sprint(oldp["price"]) != input.Get("price") {
				go FixPrice(c.GetString("id"))
			}
		}
		c.Data["json"] = 1
		allStruct := models.Query(`select id,pid from mt_goods_struct where status=1 and gid=?`, c.Gid)
		if allStruct != nil {
			for _, v := range allStruct {
				structId := v["id"].(string)
				structPid := ""
				if v["pid"] != nil {
					structPid = v["pid"].(string)
				}
				reg, _ := regexp.Compile(`^` + structId + `,|,` + structId + `,|,` + structId + `$|^` + structId + `$`)
				reg2, _ := regexp.Compile(`^` + proId + `,|,` + proId + `,|,` + proId + `$|^` + proId + `$`)
				if reg.MatchString(productStruct) {
					if reg2.MatchString(structPid) {
					} else {
						arr := strings.Split(structPid, ",")
						arr = append(arr, proId)
						str := strings.Join(arr, ",")
						str = strings.Trim(str, ",")
						models.Exec(`update mt_goods_struct set pid=? where id=?`, str, structId)
					}
				} else {
					if reg2.MatchString(structPid) {
						reg, _ := regexp.Compile(`^` + proId + `,|,` + proId + `$|^` + proId + `$`)
						str := reg.ReplaceAllString(structPid, "")
						reg1, _ := regexp.Compile(`,` + proId + `,`)
						str = reg1.ReplaceAllString(str, ",")
						models.Exec(`update mt_goods_struct set pid=? where id=?`, str, structId)
					}
				}
			}
		}
		var r models.Mt_systems_record
		r.Tid = int(res)
		if input.Get("id") == "" {
			r.Way = 2
		} else {
			r.Way = 3
		}
		r.Addtime = sword.Timeget()
		r.Table = 16
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
		bPrice := input.Get("price")
		input.Del("productstruct")
		if gid == "0" {
			if id == "" {
				shop := models.Query(`select a.id,a.name,a.freight,a.uid,b.wx_openid_gzh as openid from mt_shop a left join mt_member b on a.uid=b.id where a.status=1 and a.censoring=1 and a.style=1`)
				if shop != nil {
					for _, v := range shop {
						openid := v["openid"].(string)
						shopName := fmt.Sprint(v["name"])
						input.Set("gid", v["id"].(string))
						length := input.Get("length")
						width := input.Get("width")
						height := input.Get("height")
						number := input.Get("number")
						freight := v["freight"].(string)
						volume := sword.Divi(sword.Mult(length, sword.Mult(width, height)), "1000000")
						cellFreight := sword.Divi(sword.Mult(freight, volume), number)
						price := bPrice
						if input.Get("isvip") == "1" {
							fold := models.Query(`select fold from mt_member_vip where status=1 and name='金钻会员'`)[0]["fold"].(string)
							price = sword.Divi(sword.Mult(price, fold), "100")
						}
						endPrice := sword.Mult(sword.Sum(price, cellFreight), "3")
						input.Set("price", endPrice)
						input.Set("censoring", "0")
						res, err := models.Save("mt_product", input)
						if err != nil {
							beego.Debug(err)
						}
						data3 := map[string]map[string]interface{}{
							"first":    {"value": fmt.Sprintf(`总部有新品发布`)},
							"keyword1": {"value": shopName, "color": `#36353A`},
							"keyword2": {"value": input.Get("title"), "color": `#e31939`},
							"keyword3": {"value": input.Get("price"), "color": "#36353A"},
							"remark":   {"value": `可以在后台"管理新品"中查看详情`},
						}
						models.Push(openid, `JghVEqYW2gpPyGpdqEvhERS1AQUxTtsAwEQqjr8BOJI`, data3, models.Urlc+"/mobile/column/product_content?id="+strconv.FormatInt(res, 10), "")
					}
				}
			} else {
				// err := models.Exec(`update mt_product set price=?,mprice=? where barcode=?`, input.Get("price"), input.Get("mprice"), input.Get("barcode"))
				// if err != nil {
				// 	beego.Debug(err)
				// }
			}
		}
	}

	if id != "" {
		pid := models.Query(`select id from mt_product where status=1 and censoring=1 and barcode=?`, input.Get("barcode"))
		for _, v := range pid {
			id := v["id"].(string)
			shopcar := models.Query(`select * from mt_order_car where pid=? and status=1 and type<>1`, id)
			for _, v := range shopcar {
				pricenow, _, _ := mobile.ProductPrice(id, fmt.Sprint(v["uid"]))
				if err := models.Query(`update mt_order_car set price=? where status=1 and id=?`, pricenow, v["id"]); err != nil {
					beego.Debug(err)
				}
			}
		}
		shopcar := models.Query(`select * from mt_order_car where pid=? and status=1 and type<>1`, id)
		for _, v := range shopcar {
			pricenow, _, _ := mobile.ProductPrice(id, fmt.Sprint(v["uid"]))
			if err := models.Query(`update mt_order_car set price=? where id=?`, pricenow, v["id"]); err != nil {
				beego.Debug(err)
			}
		}
	}
}

type ProductContent struct {
	BaseController
}

func (c *ProductContent) Get() {
	id := c.GetString("id")
	if info := models.Query(`select a.*,b.pathname,c.name as cname,d.name as gname,e.name as bname,f.pathname as vname from mt_product a left join 
		mt_resources b on a.img=b.id left join mt_column c on a.cid=c.id left join mt_column d on a.gcid=d.id left join mt_brand e 
		on a.bid=e.id left join mt_resources f on a.video=f.id where a.status=1 and a.id=` + id); info != nil {
		for _, v := range info {
			keywords := fmt.Sprint(v["keywords"])
			if keywords == "" || keywords == "<nil>" {
				keywords = "''"
			}
			image := fmt.Sprint(v["image"])
			if image == "" || image == "<nil>" {
				image = "''"
			}
			v["keywords"] = models.Query(fmt.Sprintf(`select id,title from mt_keywords where id in(%v)`, keywords))
			v["picture"] = models.Query(fmt.Sprintf(`select id,pathname from mt_resources where id in(%v)`, image))
			v["diamondPrice"] = sword.Divi(sword.Mult(fmt.Sprint(v["price"]), "35"), "100")
		}
		c.Data["info"] = info[0]
		c.Data["parameter"] = models.Query(`select * from mt_product_parameter where status=1 and pid=` + id + ` order by sort desc`)
		c.Data["gid"] = c.Gid
		c.TplName = "admin/product/content.html"
	} else {
		c.Ctx.Redirect(302, "/admin/product/index")
	}
}

type ProductSpecAE struct {
	BaseController
}

func (c *ProductSpecAE) Get() {
	pid := c.GetString("pid")
	id := c.GetString("id")
	c.Data["pid"] = pid
	if pid != "" {
		if is := models.Query(`select id,title from mt_product where status=1 and id=` + pid + ` and gid=` + c.Gid); is == nil {
			c.Ctx.Redirect(302, "/admin/product/index")
		} else {
			c.TplName = "admin/product/spec_ae.html"
		}
	} else {
		if id != "" {
			if info := models.Query(`select a.*,b.pathname from mt_product_spec a left join mt_resources b on a.img=b.id join 
						(select * from mt_product where status=1 and gid=` + c.Gid + `) c on a.pid=c.id where a.id=` + id); info != nil {
				c.Data["info"] = info[0]
				c.TplName = "admin/product/spec_ae.html"
			} else {
				c.Ctx.Redirect(302, "/admin/product/index")
			}
		} else {
			c.Ctx.Redirect(302, "/admin/product/index")
		}
	}
}
func (c *ProductSpecAE) Post() {
	defer c.ServeJSON()
	input := c.Input()
	if input.Get("id") == "" {
		input.Set("addtime", sword.Gettimes("2006-01-02 15:04:05"))
	}
	if res, err := models.Save("mt_product_spec", input); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
		var r models.Mt_systems_record
		r.Tid = int(res)
		if input.Get("id") == "" {
			r.Way = 2
		} else {
			r.Way = 3
		}
		r.Addtime = sword.Timeget()
		r.Table = 35
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
}

type ProductParameterAE struct {
	BaseController
}

func (c *ProductParameterAE) Post() {
	defer c.ServeJSON()
	input := c.Input()
	if input.Get("id") == "" {
		input.Set("addtime", sword.Gettimes("2006-01-02 15:04:05"))
	}
	if res, err := models.Save("mt_product_parameter", input); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
		var r models.Mt_systems_record
		r.Tid = int(res)
		if input.Get("id") == "" {
			r.Way = 2
		} else {
			r.Way = 3
		}
		r.Addtime = sword.Timeget()
		r.Table = 36
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
}

type ColumnContent struct {
	BaseController
}

func (c *ColumnContent) Get() {
	id := c.GetString("id")
	if info := models.Query(`select a.*,b.pathname from mt_column a left join mt_resources b on a.img=b.id where a.status=1 and a.type="p" and a.id=` + id); info != nil {
		acolumn := models.Query(`select * from mt_product_attribute_column where status=1 and cid=` + id)
		for _, v := range acolumn {
			v["attribute"] = models.Query(`select * from mt_product_attribute where cid=` + v["id"].(string))
		}
		c.Data["column"] = acolumn
		c.Data["info"] = info[0]
		c.TplName = "admin/product/column_content.html"
	} else {
		c.Ctx.Redirect(302, "/admin/product/column")
	}
}

type ProductAttributeColumnAE struct {
	BaseController
}

func (c *ProductAttributeColumnAE) Get() {
	cid := c.GetString("cid")
	id := c.GetString("id")
	c.Data["cid"] = cid
	if cid != "" {
		if is := models.Query(`select id,name from mt_column where type="p" and status=1 and id=` + cid + ` and gid=` + c.Gid); is == nil {
			c.Ctx.Redirect(302, "/admin/product/column")
		} else {
			c.TplName = "admin/product/attribute_column_ae.html"
		}
	} else {
		if id != "" {
			if info := models.Query(`select a.* from mt_product_attribute_column a join (select * from mt_column where type="p" and status=1 and gid=` + c.Gid + `) 
				c on a.cid=c.id where a.cid=` + id); info != nil {
				c.Data["info"] = info[0]
				c.TplName = "admin/product/attribute_column_ae.html"
			} else {
				c.Ctx.Redirect(302, "/admin/product/column")
			}
		} else {
			c.Ctx.Redirect(302, "/admin/product/column")
		}
	}
}

func (c *ProductAttributeColumnAE) Post() {
	defer c.ServeJSON()
	input := c.Input()
	if input.Get("id") == "" {
		input.Set("addtime", sword.Gettimes("2006-01-02 15:04:05"))
	}
	if res, err := models.Save("mt_product_attribute_column", input); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
		var r models.Mt_systems_record
		r.Tid = int(res)
		if input.Get("id") == "" {
			r.Way = 2
		} else {
			r.Way = 3
		}
		r.Addtime = sword.Timeget()
		r.Table = 37
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
}

type ProductAttribute struct {
	BaseController
}

func (c *ProductAttribute) Post() {
	defer c.ServeJSON()
	input := c.Input()
	if input.Get("id") == "" {
		input.Set("addtime", sword.Gettimes("2006-01-02 15:04:05"))
	}
	if res, err := models.Save("mt_product_attribute", input); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
		var r models.Mt_systems_record
		r.Tid = int(res)
		if input.Get("id") == "" {
			r.Way = 2
		} else {
			r.Way = 3
		}
		r.Addtime = sword.Timeget()
		r.Table = 38
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
}

type ProductEvaluation struct {
	BaseController
}

func (c *ProductEvaluation) Get() {
	id := c.GetString("id")
	if info := models.Query(`select a.id from mt_product a where a.status=1 and a.id=` + id); info != nil {
		var w []string
		w = append(w, `a.status=1`)
		w = append(w, `a.sid=0`)
		ws := strings.Join(w, ` and `)
		ob := ` order by a.addtime desc`
		page, page2, num := models.Pagechange(c.GetString("page"), "")
		lt := ` limit ` + page + `,` + num
		sql := `select a.id,a.uid,a.content,a.censoring,a.addtime,a.img,a.score,b.pid,c.monicker,d.pathname,e.title from mt_product_evaluation a join 
		(select * from mt_order_car where pid=` + id + `) b on a.cid=b.id left join mt_member c on a.uid=c.id left join mt_resources d 
		on c.avatar=d.id left join mt_product e on b.pid=e.id where ` + ws + ob + lt
		sql2 := `select count(a.id) as totals from mt_product_evaluation a join 
		(select * from mt_order_car where pid=` + id + `) b on a.cid=b.id where ` + ws
		info := models.Query(sql)
		for _, v := range info {
			img := fmt.Sprint(v["img"])
			if img == "" {
				img = "''"
			}
			v["imgs"] = models.Query(fmt.Sprintf(`select pathname from mt_resources where id in(%v)`, img))
		}
		c.Data["info"] = info
		c.Data["paginator"] = models.Page(sql2, page2, num)
		c.Data["url"] = `/admin/product/evaluation?id=` + id + `&`
		c.TplName = "admin/product/evaluation.html"
	} else {
		c.Ctx.Redirect(302, "/admin/product/index")
	}
}

type ProductIntegral struct {
	BaseController
}

func (c *ProductIntegral) Get() {
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	var w []string
	w = append(w, `a.status=1`)

	search := c.GetString("search")

	if search != "" {
		w = append(w, `a.title like '%`+search+`%'`)
	}
	ws := strings.Join(w, ` and `)
	lt := ` limit ` + page + `,` + num
	sql := `select a.*,c.pathname from mt_product_integral a left join mt_resources c 
	on a.img=c.id where ` + ws + lt
	sql2 := `select count(a.id) as totals from mt_product_integral a where ` + ws
	info := models.Query(sql)
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.TplName = "admin/product/integral.html"
}

type ProductIntegralAE struct {
	BaseController
}

func (c *ProductIntegralAE) Get() {
	id := c.GetString("id")
	if id != "" {
		info := models.Query(`select a.*,b.pathname from mt_product_integral a left join mt_resources b on a.img=b.id where a.id=` + id)[0]
		c.Data["info"] = info
	}
	c.TplName = "admin/product/integral_ae.html"
}
func (c *ProductIntegralAE) Post() {
	defer c.ServeJSON()
	input := c.Input()
	input.Set("content", sword.CkeditorChange(c.GetString("content")))
	if input.Get("id") == "" {
		input.Set("addtime", sword.Gettimes("2006-01-02 15:04:05"))
	}
	if _, err := models.Save("mt_product_integral", input); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
	}
}

type ProductIntegralContent struct {
	BaseController
}

func (c *ProductIntegralContent) Get() {
	id := c.GetString("id")
	if info := models.Query(`select a.*,b.pathname from mt_product_integral a left join 
		mt_resources b on a.img=b.id where a.status=1 and a.id=` + id); info != nil {
		c.Data["info"] = info[0]
		c.TplName = "admin/product/integral_content.html"
	} else {
		c.Ctx.Redirect(302, "/admin/product/integral")
	}
}

type ProductIntegralGet struct {
	BaseController
}

func (c *ProductIntegralGet) Get() {
	id := c.GetString("id")
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	var w []string
	w = append(w, `a.pid=`+id)
	ws := strings.Join(w, ` and `)
	lt := ` limit ` + page + `,` + num
	ob := ` order by a.addtime desc `
	sql := `select a.*,b.monicker,c.pathname from mt_member_integral a 
	left join mt_member b on a.uid=b.id 
	left join mt_resources c on b.avatar=c.id 
	where ` + ws + ob + lt
	sql2 := `select count(a.id) as totals from mt_member_integral a where ` + ws
	info := models.Query(sql)
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.Data["url"] = `/admin/product/index?id=` + id + `&`
	c.TplName = "admin/product/integralList.html"
}

type ProductCopy struct {
	BaseController
}

func (c *ProductCopy) Get() {
	nows := sword.Gettimes("")
	gid := c.GetString("gid")
	id := c.GetString("id")
	shop := models.Query(`select * from mt_shop where id=?`, gid)
	platform := 0
	if shop != nil {
		if shop[0]["style"] == "1" {
			platform = 1
		}
	}
	p := models.Query(`
		select * from mt_product where id=?`, id)[0]
	if err := models.Exec(`
		insert into mt_product (gid,cid,gcid,bid,title,keywords,description,img,image,video,content,model,censoring,
			addtime,modifytime,attr,length,width,height,weight,number,price,mprice,spec,barcode,platform) 
			values (?,?,0,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, gid, p["cid"], p["bid"],
		p["title"], p["keywords"], p["description"], p["img"], p["image"], p["video"], p["content"],
		p["model"], p["censoring"], nows, nows, p["attr"], p["length"], p["width"], p["height"], p["weight"],
		p["number"], p["price"], p["mprice"], p["spec"], p["barcode"], platform); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
	}
	c.ServeJSON()
}

type ProductStatistics struct {
	BaseController
}

func (c *ProductStatistics) Get() {
	var w []string
	w = append(w, `a.paytime is not null`)
	w = append(w, `a.gid=`+c.Gid)
	w = append(w, `a.status>1`)

	page, page2, num := models.Pagechange(c.GetString("page"), "20")
	lt := ` limit ` + page + `,` + num

	ob := ` order by allmoney desc `
	gb := ` group by a.pid `
	ws := strings.Join(w, ` and `)
	info := models.Query(`
		select sum(a.num*a.price*b.price) as allmoney,sum(a.num) as sellnum,a.pid,b.title,b.barcode,c.pathname,d.name as bname 
		from mt_order_car a 
		left join mt_product b on a.pid=b.id 
		left join mt_resources c on b.img=c.id 
		left join mt_brand d on b.bid=d.id 
		where ` + ws + gb + ob + lt)

	sql2 := `select count(a.id) as totals from mt_order_car a where ` + ws + gb

	for _, v := range info {
		v["click"] = models.Query(`select sum(a.click) as num from mt_systems_reading a where a.pid=?`, v["pid"])[0]["num"]
		v["focus"] = models.Query(`select count(a.id) as count from mt_member_collection a where a.pid=?`, v["pid"])[0]["count"]
	}
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)

	c.Data["url"] = `/admin/product/statistics?`

	c.TplName = `admin/product/statistics.html`

}

func (c *ProductIntegralGet) Post() {
	iid := c.GetString("iid")
	if err := models.Exec(`update mt_member_integral set status=1 where id=` + iid); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
	}
	if fmt.Sprint(c.Data["json"]) == "1" {
		var r models.Mt_systems_record
		r.Tid, _ = strconv.Atoi(iid)
		r.Way = 72
		r.Addtime = sword.Timeget()
		r.Table = 73
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
	c.ServeJSON()
}

type ProductStructExport struct {
	BaseController
}

func (c *ProductStructExport) Get() {
	defer c.ServeJSON()
	js := make(map[string]interface{})
	c.Data["json"] = &js
	js["status"] = 0
	proStruct := models.Query(`select name,pid from mt_goods_struct where id=?`, c.GetString("id"))
	if proStruct == nil {
		return
	}
	pids := ""
	if proStruct[0]["pid"] != nil {
		pids = proStruct[0]["pid"].(string)
	}
	if pids == "" {
		js["msg"] = "没有商品"
		return
	}
	products := models.Query(`select title,barcode,spec,model,number,mprice from mt_product where id in (` + pids + `)`)
	xlsx := excelize.NewFile()
	xlsx.SetCellValue("Sheet1", "A1", "产品名称")
	xlsx.SetCellValue("Sheet1", "B1", "条形码")
	xlsx.SetCellValue("Sheet1", "C1", "产品规格")
	xlsx.SetCellValue("Sheet1", "D1", "产品型号")
	xlsx.SetCellValue("Sheet1", "E1", "装箱数")
	// xlsx.SetCellValue("Sheet1", "F1", "")
	xlsx.SetCellValue("Sheet1", "G1", "零售价")
	k := 1
	for _, p := range products {
		k += 1
		kStr := strconv.Itoa(k)
		xlsx.SetCellValue("Sheet1", "A"+kStr, p["title"])
		xlsx.SetCellValue("Sheet1", "B"+kStr, p["barcode"])
		xlsx.SetCellValue("Sheet1", "C"+kStr, p["spec"])
		xlsx.SetCellValue("Sheet1", "D"+kStr, p["model"])
		xlsx.SetCellValue("Sheet1", "E"+kStr, p["number"])
		// xlsx.SetCellValue("Sheet1", "F1", "")
		xlsx.SetCellValue("Sheet1", "G"+kStr, p["mprice"])
	}
	err := os.MkdirAll("static/xlsx", 0777)
	if err != nil {
		beego.Debug(err)
		return
	}
	fileName := proStruct[0]["name"].(string)
	pathname := "static/xlsx/" + fileName + ".xlsx"
	err = xlsx.SaveAs(pathname)
	if err != nil {
		beego.Debug(err)
		return
	}
	js["status"] = 1
	js["pathname"] = pathname
}

type ProductStructImport struct {
	BaseController
}

func (c *ProductStructImport) Post() {
	defer c.ServeJSON()
	js := make(map[string]interface{})
	c.Data["json"] = &js
	js["status"] = 0
	f, n, errup := c.GetFile("file")
	if errup != nil {
		beego.Debug(errup)
		return
	}
	defer f.Close()
	filename := n.Filename
	dirpath := "static/upload/xlsx"
	if errdir := os.MkdirAll(dirpath, 0777); errdir != nil {
		beego.Debug(errdir)
		return
	}
	err := c.SaveToFile("file", dirpath+"/"+filename)
	if err != nil {
		beego.Debug(err)
		return
	}
	xlsx, err := excelize.OpenFile(dirpath + "/" + filename)
	if err != nil {
		beego.Debug(err)
		return
	}
	rows := xlsx.GetSheetMap()
	shop := models.Query(`select id from mt_shop where status=1 and censoring=1 and style=0`)
	var shopIdArr []string
	shopIdArr = append(shopIdArr, "0")
	for _, v := range shop {
		shopIdArr = append(shopIdArr, v["id"].(string))
	}
	shopIdStr := strings.Join(shopIdArr, ",")
	var fail []string
	var has []string
	proStruct := models.Query(`select pid from mt_goods_struct where id=?`, c.GetString("id"))
	beego.Debug(proStruct[0]["pid"])
	pidStr := ""
	if proStruct[0]["pid"] != nil {
		pidStr = proStruct[0]["pid"].(string)
	}
	proIdArr := strings.Split(pidStr, ",")
	for _, v := range rows {
		row := xlsx.GetRows(v)
		for i, r := range row {
			if i < 1 {
				continue
			}
			title := r[0]
			barcode := r[1]
			model := r[3]
			if pro := models.Query(`select id,productstruct from mt_product where status=1 and censoring=1 and model=? and barcode=? and gid in (`+shopIdStr+`)`, model, barcode); pro != nil {
				proStructId := c.GetString("id")
				id := pro[0]["id"].(string)
				productstruct := ""
				if pro[0]["productstruct"] != nil {
					productstruct = pro[0]["productstruct"].(string)
				}
				reg, _ := regexp.Compile(`^` + id + `,|,` + id + `,|,` + id + `$|^` + id + `$`)
				if reg.MatchString(pidStr) {
					has = append(has, fmt.Sprint(title))
				} else {
					proIdArr = append(proIdArr, pro[0]["id"].(string))
				}
				reg1, _ := regexp.Compile(`^` + proStructId + `,|,` + proStructId + `,|,` + proStructId + `$|^` + proStructId + `$`)
				if reg1.MatchString(productstruct) {

				} else {
					arr := strings.Split(productstruct, ",")
					arr = append(arr, proStructId)
					str := strings.Trim(strings.Join(arr, ","), ",")
					models.Exec(`update mt_product set productstruct=? where id=?`, str, id)
				}
			} else {
				fail = append(fail, fmt.Sprint(title))
			}
		}
	}
	proIdStr := strings.Trim(strings.Join(proIdArr, ","), ",")
	if err := models.Query(`update mt_goods_struct set pid=? where id=?`, proIdStr, c.GetString("id")); err != nil {
		beego.Debug(err)
		return
	}
	js["status"] = 1
	js["fail"] = strings.Join(fail, ", ")
	js["has"] = strings.Join(has, ", ")
}

type ProductAddExcel struct {
	BaseController
}

func (c *ProductAddExcel) Post() {
	defer c.ServeJSON()
	var js = make(map[string]interface{})
	c.Data["json"] = &js
	f, n, errup := c.GetFile("file")
	if errup != nil {
		beego.Debug("上传文件失败:", errup)
		js["status"] = 0
		return
	}
	defer f.Close()
	filename := n.Filename
	dirpath := "static/upload/xlsx"
	if errdir := os.MkdirAll(dirpath, 0777); errdir != nil {
		beego.Debug(errdir)
		js["status"] = 0
		return
	}
	err := c.SaveToFile("file", dirpath+"/"+filename)
	if err != nil {
		beego.Debug("insert media数据失败:", err)
		js["status"] = 0
		return
	}
	xlsx, err := excelize.OpenFile(dirpath + "/" + filename)
	if err != nil {
		beego.Debug("insert media数据失败:", err)
		js["status"] = 0
		return
	}
	rows := xlsx.GetSheetMap()
	nows := sword.Gettimes("")
	var nothave []string
	var ishave []string
	freight := models.Query(`select freight from mt_shop where id=?`, c.Gid)[0]["freight"].(string)
	shop := models.Query(`select id from mt_shop where style=0 and status=1 and censoring=1`)
	var shopIdArr []string
	for _, v := range shop {
		shopIdArr = append(shopIdArr, v["id"].(string))
	}
	allShopId := strings.Join(shopIdArr, ",")
	allShopId += ",0"
	for _, v := range rows {
		row := xlsx.GetRows(v)
		for k, r := range row {
			if k > 0 {
				ps := models.Query(`select a.* from mt_product a where a.barcode=? and a.gid in(`+allShopId+`) and a.status=1`, r[1])
				if ps == nil {
					nothave = append(nothave, r[0])
					continue
				}
				p := ps[0]

				length := p["length"].(string)
				width := p["width"].(string)
				height := p["height"].(string)
				number := p["number"].(string)
				volume := sword.Divi(sword.Mult(length, sword.Mult(width, height)), "1000000")
				cellFreight := sword.Divi(sword.Mult(freight, volume), number)
				price := r[6]
				if p["isvip"] == "1" {
					vid := models.Query(`select a.vid from mt_member_vip_order a 
						left join mt_shop b on b.id=? 
						where b.uid = a.uid`, c.Gid)
					fold := "100"
					if vid != nil {
						vipFold := models.Query(`select a.fold from mt_member_vip a 
							where a.gid=0 and a.id=? and a.status=1`, vid[0]["vid"])
						if vipFold != nil {
							fold = vipFold[0]["fold"].(string)
						}
					}
					price = sword.Divi(sword.Mult(price, fold), "100")
				}
				endPrice := sword.Mult(sword.Sum(price, cellFreight), "3")
				gproduct := models.Query(`select id from mt_product where barcode=? and gid=? and status=1`, r[1], c.Gid)
				if gproduct != nil {
					models.Exec(`update mt_product set price=?,mprice=? where id=?`, endPrice, endPrice, gproduct[0]["id"])
					ishave = append(ishave, r[0])
					continue
				}
				shop := models.Query(`select * from mt_shop where id=?`, c.Gid)
				platform := 0
				if shop != nil {
					if shop[0]["style"] == "1" {
						platform = 1
					}
				}
				if err := models.Exec(`
				 	insert into mt_product 
				 	(gid,cid,bid,title,keywords,description,img,image,video,content,model,integral,
				 	ispromote,click,wholesale,isintegral,censoring,addtime,length,width,height,weight,
				 	number,price,mprice,spec,isvip,inventory,sellnum,issellnum,isw,barcode,platform) 
				 	values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?.?)`, c.Gid, p["cid"],
					p["bid"], p["title"], p["keywords"], p["description"], p["img"], p["image"], p["video"], p["content"],
					p["model"], p["integral"], p["ispromote"], p["click"], p["wholesale"], p["censoring"],
					nows, p["length"], p["width"], p["height"], p["weight"],
					r[4], endPrice, price, r[2], p["isvip"], p["inventory"], 0, 1, p["isw"], p["barcode"], platform); err != nil {
					beego.Debug(err)
				}
			}
		}
		// for _, r := range row {
		// 	pid := models.Query(`select a.id from mt_product a left join mt_shop b on a.gid=b.id
		// 		where a.status=1 and a.censoring=1 and (a.gid=0 or b.style=0) and a.barcode=?`, r[1])
		// 	if pid != nil {
		// 		if ishave := models.Query(`select id from mt_order_car where uid=? and pid=? and status=1 and type<>1`, c.Uid, pid[0]["id"]); ishave != nil {
		// 			if err := models.Exec(`update mt_order_car set num=? where id=?`, r[2], ishave[0]["id"]); err != nil {
		// 				beego.Debug(err)
		// 			}
		// 		} else {
		// 			price, _, tid := mobile.ProductPrice(fmt.Sprint(pid[0]["id"]), c.Uid)
		// 			var t = 0
		// 			if tid != "0" {
		// 				t = 2
		// 			}
		// 			if err := models.Exec(`insert into mt_order_car (pid,gid,num,uid,price,addtime,spec,type,status) values (?,0,?,?,?,?,?,?,1)`, pid[0]["id"], r[2], c.Uid, price, nows, 0, t); err != nil {
		// 				beego.Debug(err)
		// 			}
		// 		}
		// 	} else {
		// 		nothave = append(nothave, r[0])
		// 	}
		// }
	}
	js["status"] = 1
	var msg string
	if len(nothave) == 0 {
		msg = "导入成功"
	} else {
		nothaves := strings.Join(nothave, ",")
		msg = nothaves + "未导入,"
		ishaves := strings.Join(ishave, ",")
		msg = msg + ishaves + "已存在"
	}
	js["msg"] = msg
}

type GetProduct struct {
	BaseController
}

func (c *GetProduct) Get() {
	defer c.ServeJSON()
	js := make(map[string]interface{})
	c.Data["json"] = &js
	if c.GetString("once") == "1" {
		js["status"] = -1
		if c.GetSession("getproduct") == "1" {
			js["status"] = 1
			js["pathname"] = c.GetSession("getproductPathname")
			c.DelSession("getproduct")
			c.DelSession("getproductPathname")
		} else if c.GetSession("getproduct") == "0" {
			js["status"] = 0
			c.DelSession("getproduct")
			c.DelSession("getproductPathname")
		}
		return
	}
	c.EnableRender = false
	bid := c.GetString("bid")
	cid := c.GetString("cid")
	program := c.GetString("program")
	var title string
	var w []string
	var allShopId string
	shop := models.Query(`select id from mt_shop where status=1 and censoring=1 and style=0`)
	var shopIdArr []string
	shopIdArr = append(shopIdArr, "0")
	for _, v := range shop {
		shopIdArr = append(shopIdArr, v["id"].(string))
	}
	allShopId = strings.Join(shopIdArr, ",")
	w = append(w, `a.status=1`)
	w = append(w, `a.censoring=1`)
	w = append(w, "a.gid in("+allShopId+")")
	if bid != "" {
		title = models.Query(`select name from mt_brand where id=?`, bid)[0]["name"].(string)
		w = append(w, `a.bid=`+bid)
	} else if program != "" {
		program := models.Query("select * from mt_program where id=" + program)
		title = program[0]["name"].(string)
		w = append(w, `a.id in (`+program[0]["pid"].(string)+`)`)
	} else {
		title = models.Query(`select name from mt_column where id=?`, cid)[0]["name"].(string)
		var cids []string
		cids = append(cids, cid)
		column := models.Query(`select id,name from mt_column where pid=? and status=1`, cid)
		for _, v := range column {
			id := v["id"].(string)
			cids = append(cids, id)
			columnson := models.Query(`select id,name from mt_column where pid=? and status=1`, id)
			for _, s := range columnson {
				cids = append(cids, s["id"].(string))
			}
		}
		cidss := strings.Join(cids, ",")
		w = append(w, `a.cid in (`+cidss+`)`)
	}
	ws := strings.Join(w, ` and `)

	info := models.Query(`
		select a.title,a.model,a.barcode,a.width,a.height,a.weight,a.length,a.barcode,a.number,a.image,a.price,b.pathname 
		from mt_product a left join mt_resources b on a.img=b.id where ` + ws)
	beego.Debug(info)
	beego.Debug(`
		select a.title,a.model,a.barcode,a.width,a.height,a.weight,a.length,a.barcode,a.number,a.image,a.price,b.pathname 
		from mt_product a left join mt_resources b on a.img=b.id where ` + ws)
	xlsx := excelize.NewFile()
	// index := xlsx.NewSheet("Sheet1")

	xlsx.SetCellValue("Sheet1", "A1", "图片")
	xlsx.SetCellValue("Sheet1", "B1", "产品名称")
	xlsx.SetCellValue("Sheet1", "C1", "产品型号")
	xlsx.SetCellValue("Sheet1", "D1", "条形码")
	xlsx.SetCellValue("Sheet1", "E1", "尺寸(长宽高/m)")
	xlsx.SetCellValue("Sheet1", "F1", "重量(kg)")
	xlsx.SetCellValue("Sheet1", "G1", "装箱数")
	xlsx.SetCellValue("Sheet1", "H1", "价格")
	// var ks int
	vip := models.Query(`select name,fold from mt_member_vip where gid=? and status=1`, c.Gid)
	for k, v := range info {
		k = (k+1)*4 - 2
		price := fmt.Sprint(v["price"])
		xlsx.SetCellValue("Sheet1", fmt.Sprintf("B%v", k), fmt.Sprint(v["title"]))
		xlsx.SetCellValue("Sheet1", fmt.Sprintf("C%v", k), fmt.Sprint(v["model"]))
		xlsx.SetCellValue("Sheet1", fmt.Sprintf("D%v", k), fmt.Sprint(v["barcode"]))
		xlsx.SetCellValue("Sheet1", fmt.Sprintf("E%v", k), fmt.Sprintf(`%v*%v*%v`, v["length"], v["width"], v["height"]))
		xlsx.SetCellValue("Sheet1", fmt.Sprintf("F%v", k), fmt.Sprint(v["weight"]))
		xlsx.SetCellValue("Sheet1", fmt.Sprintf("G%v", k), fmt.Sprint(v["number"]))
		xlsx.SetCellValue("Sheet1", fmt.Sprintf("H%v", k), price)

		char := 'H'
		for i, v := range vip {
			letter := int(char) + i + 1
			col := string(letter) + strconv.Itoa(k)
			fold := v["fold"].(string)
			name := v["name"].(string) + "价"
			foldPrice := sword.Divi(sword.Mult(price, fold), "100")
			xlsx.SetCellValue("Sheet1", string(letter)+"1", name)
			xlsx.SetCellValue("Sheet1", col, foldPrice)
			for i := 0; i < 3; i++ {
				col1 := string(letter) + strconv.Itoa(k+1+i)
				xlsx.MergeCell("Sheet1", col, col1)
			}
		}

		xlsx.MergeCell("Sheet1", fmt.Sprintf("A%v", k), fmt.Sprintf("A%v", k+1))
		xlsx.MergeCell("Sheet1", fmt.Sprintf("B%v", k), fmt.Sprintf("B%v", k+1))
		xlsx.MergeCell("Sheet1", fmt.Sprintf("C%v", k), fmt.Sprintf("C%v", k+1))
		xlsx.MergeCell("Sheet1", fmt.Sprintf("D%v", k), fmt.Sprintf("D%v", k+1))
		xlsx.MergeCell("Sheet1", fmt.Sprintf("E%v", k), fmt.Sprintf("E%v", k+1))
		xlsx.MergeCell("Sheet1", fmt.Sprintf("F%v", k), fmt.Sprintf("F%v", k+1))
		xlsx.MergeCell("Sheet1", fmt.Sprintf("G%v", k), fmt.Sprintf("G%v", k+1))
		xlsx.MergeCell("Sheet1", fmt.Sprintf("H%v", k), fmt.Sprintf("H%v", k+1))

		xlsx.MergeCell("Sheet1", fmt.Sprintf("A%v", k), fmt.Sprintf("A%v", k+2))
		xlsx.MergeCell("Sheet1", fmt.Sprintf("B%v", k), fmt.Sprintf("B%v", k+2))
		xlsx.MergeCell("Sheet1", fmt.Sprintf("C%v", k), fmt.Sprintf("C%v", k+2))
		xlsx.MergeCell("Sheet1", fmt.Sprintf("D%v", k), fmt.Sprintf("D%v", k+2))
		xlsx.MergeCell("Sheet1", fmt.Sprintf("E%v", k), fmt.Sprintf("E%v", k+2))
		xlsx.MergeCell("Sheet1", fmt.Sprintf("F%v", k), fmt.Sprintf("F%v", k+2))
		xlsx.MergeCell("Sheet1", fmt.Sprintf("G%v", k), fmt.Sprintf("G%v", k+2))
		xlsx.MergeCell("Sheet1", fmt.Sprintf("H%v", k), fmt.Sprintf("H%v", k+2))

		xlsx.MergeCell("Sheet1", fmt.Sprintf("A%v", k), fmt.Sprintf("A%v", k+3))
		xlsx.MergeCell("Sheet1", fmt.Sprintf("B%v", k), fmt.Sprintf("B%v", k+3))
		xlsx.MergeCell("Sheet1", fmt.Sprintf("C%v", k), fmt.Sprintf("C%v", k+3))
		xlsx.MergeCell("Sheet1", fmt.Sprintf("D%v", k), fmt.Sprintf("D%v", k+3))
		xlsx.MergeCell("Sheet1", fmt.Sprintf("E%v", k), fmt.Sprintf("E%v", k+3))
		xlsx.MergeCell("Sheet1", fmt.Sprintf("F%v", k), fmt.Sprintf("F%v", k+3))
		xlsx.MergeCell("Sheet1", fmt.Sprintf("G%v", k), fmt.Sprintf("G%v", k+3))
		xlsx.MergeCell("Sheet1", fmt.Sprintf("H%v", k), fmt.Sprintf("H%v", k+3))
		// ks = k + 3
	}
	xlsx.SetColWidth("Sheet1", "A", "M", 30)
	// styleID, err := xlsx.NewStyle(`{"alignment":{"horizontal":"","vertical":"center"}}`)
	// if err != nil {
	// 	beego.Debug(err)
	// }
	// xlsx.SetCellStyle("Sheet1", fmt.Sprintf("A%v", ks), fmt.Sprintf("G%v", ks), styleID)
	// xlsx.SetActiveSheet(index)
	err := os.MkdirAll("static/xlsx", 0777)
	nowtimes := fmt.Sprint(time.Now().Unix())
	title = strings.Replace(title, "/", "-", -1)
	c.SetSession("getproductPathname", "/static/xlsx/"+title+nowtimes+".xlsx")
	if err != nil {
		beego.Debug(err)
		c.SetSession("getproduct", "0")
		return
	}
	err = xlsx.SaveAs("static/xlsx/" + title + nowtimes + ".xlsx")
	if err != nil {
		beego.Debug(err)
		c.SetSession("getproduct", "0")
		return
	}
	xlsx2, err := excelize.OpenFile("static/xlsx/" + title + nowtimes + ".xlsx")
	if err != nil {
		beego.Debug(err)
		c.SetSession("getproduct", "0")
		return
	}
	// Insert a picture.
	for k, v := range info {
		k = (k+1)*4 - 2
		pathname := fmt.Sprint(v["pathname"])
		pathname = strings.Replace(pathname, "https://tcsc.oss-cn-hangzhou.aliyuncs.com/", "", -1)
		pathname = strings.Replace(pathname, "?x-oss-process=style/base", "", -1)
		pathnameArr := strings.Split(pathname, ".")
		ext := strings.ToLower(path.Ext(pathname))
		pathname = pathnameArr[0] + ext
		if pathname != "" && pathname != "<nil>" {
			err := xlsx2.AddPicture("Sheet1", fmt.Sprintf("A%v", k), pathname, `{"lock_aspect_ratio":false,"locked":true,"print_obj":true,"x_scale":0.2,"y_scale":0.2}`)
			if err != nil {
				beego.Debug(err)
			}
		}
		// y := k * 5
		// image := fmt.Sprint(v["image"])
		// if image != "" && image != "<nil>" {
		// 	imgs := models.Query(`select pathname from mt_resources where id in(` + image + `)`)
		// 	for k2, i := range imgs {
		// 		path := fmt.Sprint(i["pathname"])
		// 		path = strings.Trim(path, "/")
		// 		x := (k2 + 1) * 6
		// 		err := xlsx2.AddPicture("Sheet1", fmt.Sprintf("A%v", k), path, fmt.Sprintf(`{"lock_aspect_ratio":false,"locked":true,"print_obj":true,
		// 			"x_scale":0.2,"y_scale":0.2,"x_offset":%v,"y_offset":%v}`, x, y))
		// 		if err != nil {
		// 			beego.Debug(err)
		// 		}
		// 	}
		// }
	}
	// Save the xlsx file with the origin path.
	err = xlsx2.Save()
	if err != nil {
		beego.Debug(err)
		c.SetSession("getproduct", "0")
		return
	}
	c.SetSession("getproduct", "1")
	js["pathname"] = c.GetSession("getproductPathname")
}

type ShopGetProduct struct {
	BaseController
}

func (c *ShopGetProduct) Get() {
	bid := c.GetString("bid")
	cid := c.GetString("cid")
	var title string
	var w []string
	var allShopId string
	shop := models.Query(`select id from mt_shop where status=1 and censoring=1 and style=0`)
	var shopIdArr []string
	shopIdArr = append(shopIdArr, "0")
	for _, v := range shop {
		shopIdArr = append(shopIdArr, v["id"].(string))
	}
	allShopId = strings.Join(shopIdArr, ",")
	w = append(w, "a.status=1")
	w = append(w, "a.censoring=1")
	w = append(w, "a.gid in("+allShopId+")")
	if bid != "" {
		title = models.Query(`select name from mt_brand where id=?`, bid)[0]["name"].(string)
		w = append(w, "a.bid="+bid)
	} else {
		title = models.Query(`select name from mt_column where id=?`, cid)[0]["name"].(string)
		var cids []string
		cids = append(cids, cid)
		column := models.Query(`select id,name from mt_column where pid=? and status=1`, cid)
		for _, v := range column {
			id := v["id"].(string)
			cids = append(cids, id)
			columnson := models.Query(`select id,name from mt_column where pid=? and status=1`, id)
			for _, s := range columnson {
				cids = append(cids, s["id"].(string))
			}
		}
		cidss := strings.Join(cids, ",")
		w = append(w, `a.cid in (`+cidss+`)`)
	}
	ws := strings.Join(w, ` and `)
	products := models.Query(`select a.title,a.spec,a.number,a.price,a.barcode from mt_product a 
			where ` + ws)

	xlsx := excelize.NewFile()
	xlsx.SetCellValue("sheet1", "A1", "产品名称")
	xlsx.SetCellValue("Sheet1", "B1", "条形码")
	xlsx.SetCellValue("Sheet1", "C1", "产品规格")
	xlsx.SetCellValue("Sheet1", "E1", "装箱数")
	xlsx.SetCellValue("Sheet1", "G1", "零售价")

	for k, v := range products {
		k += 2
		xlsx.SetCellValue("Sheet1", "A"+fmt.Sprint(k), v["title"])
		xlsx.SetCellValue("Sheet1", "B"+fmt.Sprint(k), v["barcode"])
		xlsx.SetCellValue("Sheet1", "C"+fmt.Sprint(k), v["spec"])
		xlsx.SetCellValue("Sheet1", "E"+fmt.Sprint(k), v["number"])
		xlsx.SetCellValue("Sheet1", "G"+fmt.Sprint(k), v["price"])
	}
	nowtimes := fmt.Sprint(time.Now().Unix())
	err := os.MkdirAll("static/xlsx", 0777)
	if err != nil {
		beego.Debug(err)
		return
	}
	err = xlsx.SaveAs("static/xlsx/" + title + nowtimes + ".xlsx")
	if err != nil {
		beego.Debug(err)
		return
	}
	c.Ctx.Redirect(302, "/static/xlsx/"+title+nowtimes+".xlsx")
}

type ProductStruct struct {
	BaseController
}

func (c *ProductStruct) Get() {
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	lt := ` limit ` + page + `,` + num
	sql := `select a.id,a.name,a.supe,a.type,b.pathname 
	from mt_goods_struct a 
	left join mt_resources b on a.img=b.id 
	where a.status=1` + lt
	info := models.Query(sql)
	if info != nil {
		for _, v := range info {
			if v["supe"] == "0" {
				v["supeName"] = ""
			} else {
				name := models.Query(`select name from mt_goods_struct where id=?`, v["supe"])
				v["supeName"] = name[0]["name"]
			}
		}
	}
	sql2 := `select count(*) as totals from mt_goods_struct where status=1`
	c.Data["info"] = info
	beego.Debug(c.Data["info"])
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.TplName = "admin/product/struct.html"
}

type ProductStructAE struct {
	BaseController
}

func (c *ProductStructAE) Get() {
	id := c.GetString("id")
	// if id == "" {
	// 	supe := models.Query(`select a.id,a.name,b.pathname from mt_goods_struct a
	// 		left join mt_resources b on a.img=b.id
	// 		where a.status=1`)
	// 	c.Data["supe"] = supe
	// } else {
	if id == "" {

	} else {
		c.Data["id"] = id
		info := models.Query(`select a.name,a.cid,a.img,a.pid,a.themeColor,a.introduce,b.pathname from mt_goods_struct a 
				left join mt_resources b on a.img=b.id 
				where a.status=1 and a.id=?`, id)
		c.Data["info"] = info[0]
	}
	// supe := models.Query(`select supe from mt_goods_struct where status=1 and id=?`, id)
	// if supe[0]["supe"].(string) != "0" {
	// 	info := models.Query(`select cid,pid from mt_goods_struct where id=?`, supe[0]["supe"])
	// 	cid := info[0]["cid"]
	// 	pid := info[0]["pid"]
	// 	var res []interface{}
	// 	if cid != nil && pid != nil {
	// 		cidArr := strings.Split(cid.(string), ",")
	// 		for _, v := range cidArr {
	// 			ctn := make(map[string]interface{})
	// 			cidName := models.Query(`select name from mt_column where id=?`, v)[0]["name"]
	// 			var cids []string
	// 			cids = append(cids, v)
	// 			column1 := models.Query(`select id from mt_column where status=1 and pid=?`, v)
	// 			for _, c1 := range column1 {
	// 				cids = append(cids, c1["id"].(string))
	// 				column2 := models.Query(`select id from mt_column where status=1 and pid=?`, c1["id"])
	// 				for _, c2 := range column2 {
	// 					cids = append(cids, c2["id"].(string))
	// 				}
	// 			}
	// 			cidStr := strings.Join(cids, ",")
	// 			ctn["id"] = v
	// 			ctn["name"] = cidName
	// 			ctn["product"] = models.Query(`select id,title
	// 				from mt_product where id in(` + pid.(string) + `) and cid in(` + cidStr + `)`)
	// 			res = append(res, ctn)
	// 		}
	// 	}
	// 	c.Data["column"] = res
	// } else {
	// column := models.Query(`select id,name from mt_column where type='p' and status=1 and pid=0`)
	// for _, c := range column {
	// 	var cids []string
	// 	cids = append(cids, c["id"].(string))
	// 	column1 := models.Query(`select id from mt_column where status=1 and pid=?`, c["id"])
	// 	for _, c1 := range column1 {
	// 		cids = append(cids, c1["id"].(string))
	// 		column2 := models.Query(`select id from mt_column where status=1 and pid=?`, c1["id"])
	// 		for _, c2 := range column2 {
	// 			cids = append(cids, c2["id"].(string))
	// 		}
	// 	}
	// 	cidsStr := strings.Join(cids, ",")
	// 	c["product"] = models.Query(`select a.id,a.title
	// 				from mt_product a
	// 				join (select * from mt_shop
	// 					where style=0 and status=1 and censoring=1) b on a.gid=b.id
	// 				where a.status=1 and a.censoring=1 and a.cid in(` + cidsStr + `)
	// 				order by a.cid`)
	// }
	// c.Data["column"] = column
	// 	}
	// }
	c.TplName = "admin/product/struct_ae.html"
}

func (c *ProductStructAE) Post() {
	json := make(map[string]interface{})
	c.Data["json"] = &json
	id := c.GetString("id")
	name := c.GetString("name")
	themeColor := c.GetString("themeColor")
	introduce := c.GetString("introduce")
	// cid := strings.Join(c.GetStrings("cid"), ",")
	// pid := strings.Join(c.GetStrings("pid"), ",")
	img := c.GetString("img")
	if id == "" {
		// 	supe := c.GetString("supe")
		if err := models.Exec(`insert into mt_goods_struct (name,img,themeColor,introduce) values (?,?,?,?)`, name, img, themeColor, introduce); err != nil {
			beego.Debug(err)
			json["status"] = 0
		} else {
			json["status"] = 1
		}
	} else {
		if err := models.Exec(`update mt_goods_struct set name=?,img=?,themeColor=?,introduce=? where id=?`, name, img, themeColor, introduce, id); err != nil {
			beego.Debug(err)
			json["status"] = 0
		} else {
			json["status"] = 1
		}
	}
	c.ServeJSON()
}

type ProductStructImg struct {
	BaseController
}

func (c *ProductStructImg) Get() {
	gid := c.Gid
	id := c.GetString("id")
	c.Data["name"] = models.Query(`select name from mt_goods_struct where id=?`, id)[0]["name"]
	var imgArr [10]interface{}
	info := models.Query(`select id,imgs,introduce from mt_product_struct_imgs where sid=? and gid=?`, id, gid)
	if info != nil {
		img := models.Query(`select id,pathname from mt_resources where id in(` + fmt.Sprint(info[0]["imgs"]) + `)`)
		if img != nil {
			for i, v := range img {
				imgArr[i] = v
			}
		}
		c.Data["info"] = info[0]
	}
	c.Data["sid"] = id
	c.Data["images"] = imgArr
	c.TplName = "admin/product/struct_img.html"
}

func (c *ProductStructImg) Post() {
	defer c.ServeJSON()
	js := make(map[string]interface{})
	c.Data["json"] = &js
	input := c.Input()
	input.Set("imgs", strings.Replace(strings.Trim(strings.Join(c.GetStrings("img"), ","), ","), ",,", ",", -1))
	input.Del("img")
	input.Set("gid", c.Gid)
	input.Set("time", sword.Gettimes(""))
	if _, err := models.Save("mt_product_struct_imgs", input); err != nil {
		beego.Debug(err)
		js["status"] = 0
	} else {
		js["status"] = 1
	}
}

// type ProductStructImgData struct {
// 	Data []ColumnDatas `json:"data" form:"data"`
// 	Id   string        `json:"id" from:"id"`
// }

// type ColumnDatas struct {
// 	Id        string `json:"id" from:"id"`
// 	Images    string `json:"images" from:"images"`
// 	Introduce string `json:"introduce" from:"introduce"`
// }

// func (c *ProductStructImg) Post() {
// 	defer c.ServeJSON()
// 	var inputData = ProductStructImgData{}
// 	js := make(map[string]interface{})
// 	c.Data["json"] = &js
// 	js["status"] = 1
// 	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &inputData); err != nil {
// 		beego.Debug(err)
// 		js["status"] = 0
// 		return
// 	}
// 	id := inputData.Id
// 	nowtime := time.Now().Local().Format("2006-01-02 15:04:05")
// 	for _, v := range inputData.Data {
// 		if res := models.Query(`select id from mt_goods_struct_imgs where sid=? and cid=? and gid=?`, id, v.Id, c.Gid); res != nil {
// 			err := models.Exec(`update mt_goods_struct_imgs set imgs=?,introduce=?,time=? where sid=? and cid=? and gid=?`, v.Images, v.Introduce, nowtime, id, v.Id, c.Gid)
// 			if err != nil {
// 				beego.Debug(err)
// 				js["status"] = 0
// 				return
// 			}
// 		} else {
// 			err := models.Exec(`insert into mt_goods_struct_imgs (imgs,cid,gid,introduce,time,sid) values(?,?,?,?,?,?)`, v.Images, v.Id, c.Gid, v.Introduce, nowtime, id)
// 			if err != nil {
// 				beego.Debug(err)
// 				js["status"] = 0
// 				return
// 			}
// 		}
// 	}
// }

type ProductImgExport struct {
	BaseController
}

func (c *ProductImgExport) Get() {
	json := make(map[string]interface{})
	c.Data["json"] = &json
	id := c.GetString("id")
	product := models.Query(`select title,img,image from mt_product where id=?`, id)
	if product != nil && product[0]["img"] != nil {
		var path []string
		pro := make(map[string]interface{})
		imgStrs := product[0]["img"].(string) + "," + product[0]["image"].(string)
		pathname := models.Query(`select pathname from mt_resources where id in(` + imgStrs + `)`)
		for _, v := range pathname {
			path = append(path, v["pathname"].(string))
		}
		pro["name"] = product[0]["title"]
		pro["imgs"] = path
		json["result"] = pro
		json["status"] = 1
	} else {
		json["status"] = 0
	}
	c.ServeJSON()
}

type ProductsAllExport struct {
	BaseController
}

func (c *ProductsAllExport) Get() {
	xlsx := excelize.NewFile()
	xlsx.SetCellValue("Sheet1", "A1", "产品编号")
	xlsx.SetCellValue("Sheet1", "B1", "产品名称")
	xlsx.SetCellValue("Sheet1", "C1", "产品条码")
	xlsx.SetCellValue("Sheet1", "D1", "产品条码")
	xlsx.SetCellValue("Sheet1", "E1", "装箱规格")
	xlsx.SetCellValue("Sheet1", "F1", "装箱数")
	xlsx.SetCellValue("Sheet1", "G1", "外箱尺寸(长宽高/cm)")
	xlsx.SetCellValue("Sheet1", "H1", "体积(立方)")
	xlsx.SetCellValue("Sheet1", "I1", "金钻会员价")
	xlsx.SetCellValue("Sheet1", "J1", "钻石会员价")
	var w []string
	if c.GetString("censoring") != "" {
		w = append(w, `censoring=`+c.GetString("censoring"))
	}
	if c.GetString("recommend") != "" {
		w = append(w, `recommend=`+c.GetString("recommend"))
	}
	bid := c.GetString("bid")
	search := c.GetString("search")
	cid := c.GetString("cid")

	w = append(w, `status=1`)
	if search != "" {
		w = append(w, `(title like '%`+search+`%' or model like '%`+search+`%' or keywords like '%`+search+`%')`)
	}
	if cid != "" {
		w = append(w, `cid=`+cid)
	}
	ws := strings.Join(w, ` and `)
	var brands []orm.Params
	if bid != "" {
		brands = models.Query(`select id,name from mt_brand where status=1 and censoring=1 and id=` + bid)
	} else {
		brands = models.Query(`select id,name from mt_brand where status=1 and censoring=1`)
	}
	shopId := models.Query(`select id from mt_shop where censoring=1 and status=1 and style=0`)
	var shopIdArr []string
	shopIdArr = append(shopIdArr, "0")
	for _, s := range shopId {
		shopIdArr = append(shopIdArr, s["id"].(string))
	}
	allShopId := strings.Join(shopIdArr, ",")
	i := 1
	var key string
	for _, b := range brands {
		i += 1
		key = strconv.Itoa(i)
		bids := b["id"]
		brandName := b["name"].(string)
		xlsx.SetCellValue("Sheet1", "A"+key, brandName)
		products := models.Query(`select id,title,barcode,number,spec,isvip,length,width,height,price from mt_product 
			where `+ws+` and gid in(`+allShopId+`) and bid=?`, bids)
		if products != nil {
			for _, p := range products {
				i += 1
				key = strconv.Itoa(i)
				width := p["width"].(string)
				length := p["length"].(string)
				height := p["height"].(string)
				volume := sword.Divi(sword.Mult(width, sword.Mult(length, height)), "1000000")
				boxSize := length + "*" + width + "*" + height
				price := p["price"].(string)
				var goldDiamondPrice string
				var diamondPrice string
				if p["isvip"].(string) == "1" {
					fold := models.Query(`select fold from mt_member_vip where name='金钻会员' and status=1`)[0]["fold"].(string)
					goldDiamondPrice = sword.Divi(sword.Mult(price, fold), "100")
					fold = models.Query(`select fold from mt_member_vip where name='钻石会员' and status=1`)[0]["fold"].(string)
					diamondPrice = sword.Divi(sword.Mult(price, fold), "100")
				}
				xlsx.SetCellValue("Sheet1", "A"+key, p["id"])
				xlsx.SetCellValue("Sheet1", "B"+key, p["title"])
				xlsx.SetCellValue("Sheet1", "C"+key, brandName)
				xlsx.SetCellValue("Sheet1", "D"+key, p["barcode"])
				xlsx.SetCellValue("Sheet1", "E"+key, p["spec"])
				xlsx.SetCellValue("Sheet1", "F"+key, p["number"])
				xlsx.SetCellValue("Sheet1", "G"+key, boxSize)
				xlsx.SetCellValue("Sheet1", "H"+key, volume)
				xlsx.SetCellValue("Sheet1", "I"+key, goldDiamondPrice)
				xlsx.SetCellValue("Sheet1", "J"+key, diamondPrice)
			}
		}
	}
	err := os.MkdirAll("static/xlsx", 0777)
	if err != nil {
		beego.Debug(err)
		return
	}
	name := "allProdcuts"
	err = xlsx.SaveAs("static/xlsx/" + name + ".xlsx")
	if err != nil {
		beego.Debug(err)
		return
	}
	c.Ctx.Redirect(302, "/static/xlsx/"+name+".xlsx")
}

type ProductBrandClassify struct {
	BaseController
}

func (c *ProductBrandClassify) Get() {
	c.Data["column"] = models.Query(`select id,name from mt_brand where status=1 and censoring=1 and gid=0 order by sort desc, modifytime desc`)
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	var w []string
	id := c.GetString("id")
	c.Data["id"] = id
	w = append(w, `a.status=1`)
	if c.Gid != "0" {
		w = append(w, `a.gid=`+c.Gid)
	} else {
		if id != "" {
			w = append(w, `a.gid=`+id)
		} else {
			w = append(w, `(a.gid=0 or d.style=0)`)
		}
	}
	censoring := c.GetString("censoring")
	recommend := c.GetString("recommend")
	is_show := c.GetString("is_show")
	c.Data["censoring"] = censoring
	c.Data["recommend"] = recommend
	c.Data["is_show"] = is_show
	if censoring != "" {
		w = append(w, `a.censoring=`+censoring)
	}
	if recommend != "" {
		w = append(w, `a.recommend=`+recommend)
	}
	if is_show != "" {
		w = append(w, `a.is_show=`+is_show)
	}
	search := c.GetString("search")
	c.Data["search"] = search
	bid := c.GetString("bid")
	if bid != "" {
		w = append(w, `a.bid=`+bid)
	}
	if c.GetString("clear") == "1" {
		c.Data["search"] = ""
		c.Data["censoring"] = ""
		c.Data["recommend"] = ""
		c.Data["is_show"] = ""
	}
	c.Data["bid"] = bid
	if search != "" {
		w = append(w, `(a.title like '%`+search+`%' or a.model like '%`+search+`%' or a.keywords like '%`+search+`%')`)
	}
	ws := strings.Join(w, ` and `)
	lt := ` limit ` + page + `,` + num
	sql := `select a.*,b.name as cname,c.pathname,d.name as gname from mt_product a left join mt_column b on a.cid=b.id left join mt_resources c 
	on a.img=c.id left join mt_shop d on d.id=a.gid where ` + ws + ` order by a.censoring desc,a.recommend desc` + lt
	sql2 := `select count(a.id) as totals from mt_product a left join mt_shop d on a.gid=d.id where ` + ws
	info := models.Query(sql)
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	if id != "" {
		c.Data["url"] = `/admin/shop/product?id=` + id + `&bid=` + bid + `&search=` + search + `&`
		c.Data["urlc"] = `/admin/shop/product?id=` + id + `&bid=` + bid + `&`
	} else {
		c.Data["url"] = `/admin/product/brand_classify?id=` + id + `&bid=` + bid + `&search=` + search + `&`
		c.Data["urlc"] = `/admin/product/brand_classify?`
	}
	c.TplName = "admin/product/brand_classify.html"
}

type ProZipExport struct {
	BaseController
}

func (c *ProZipExport) Get() {
	id := c.GetString("id")
	pro := models.Query(`select title,img,image,content from mt_product where id=?`, id)[0]
	var imgs []string
	var imgs1 []string
	img := fmt.Sprint(pro["img"])
	if img != "" && img != "<nil>" {
		pathname := models.Query(`select pathname from mt_resources where id=?`, img)
		if pathname != nil {
			imgs = append(imgs, fmt.Sprint(pathname[0]["pathname"]))
		}
	}
	image := fmt.Sprint(pro["image"])
	if image != "" && image != "<nil>" {
		pathnames := models.Query(`select pathname from mt_resources where id in(` + image + `)`)
		if pathnames != nil {
			for _, p := range pathnames {
				imgs = append(imgs, fmt.Sprint(p["pathname"]))
			}
		}
	}
	content := fmt.Sprint(pro["content"])
	if content != "" {
		imgs1 = sword.UeditorImg(content)
	}
	imgs = append(imgs, imgs1...)
	var images []string
	//var images []string = []string{
	//	"static/uppic/function/2019-11-29/1574990740698583500.jpg",
	//}
	for _, i := range imgs {
		pathname := i
		pathname = strings.Replace(pathname, "https://tcsc.oss-cn-hangzhou.aliyuncs.com/", "", -1)
		pathname = strings.Replace(pathname, "?x-oss-process=style/base", "", -1)
		pathname = strings.TrimLeft(pathname, "/")
		ext := path.Ext(pathname)
		source := strings.TrimRight(pathname, ext) + "-source" + ext
		isExists, _ := PathExists(source)
		if isExists {
			images = append(images, source)
		} else {
			source = pathname + "-source" + strings.ToLower(ext)
			isExists, _ = PathExists(source)
			if isExists {
				images = append(images, source)
			} else {
				images = append(images, pathname)
			}
		}
	}
	js := make(map[string]interface{})
	c.Data["json"] = &js
	defer c.ServeJSON()
	zipPath, err := ImagesBale(images, fmt.Sprint(pro["title"]))
	if err != nil {
		js["status"] = 0
		return
	}
	js["pathname"] = zipPath
	js["status"] = 1
}

func ImagesBale(images []string, fileName string) (string, error) {
	time := fmt.Sprint(time.Now().Unix())
	zipName := "static/orderimg/img(" + time + ").zip"
	file, err := os.Create(zipName)
	if err != nil {
		beego.Debug(err)
		return "", err
	}
	defer file.Close()
	zw := zip.NewWriter(file)
	defer zw.Close()
	for i, v := range images {
		// pathname := strings.TrimLeft(v, "/")

		// beego.Debug(pathname)
		imgFile, err := os.Open(v)
		if err != nil {
			beego.Debug(err)
			return "", err
		}
		defer imgFile.Close()
		fileInfo, err := imgFile.Stat()
		if err != nil {
			beego.Debug(err)
			return "", err
		}
		InfoHeader, err := zip.FileInfoHeader(fileInfo)
		if err != nil {
			beego.Debug(err)
			return "", err
		}
		ext := strings.ToLower(path.Ext(v))
		InfoHeader.Name = fileName + "(" + strconv.Itoa(i) + ")" + ext
		fileWriter, err := zw.CreateHeader(InfoHeader)
		if err != nil {
			beego.Debug(err)
			return "", err
		}
		io.Copy(fileWriter, imgFile)

	}
	return zipName, nil
}
